package controllers

import play.api.mvc.{AbstractController, ControllerComponents}
import tool.{FormTool, Tool}
import utils.Utils

import java.io.File
import javax.inject.Inject
import scala.annotation.tailrec
import scala.concurrent.ExecutionContext.Implicits.global

/** Created by yz on 6/4/2021
  */
class DownloadController @Inject() (cc: ControllerComponents) extends AbstractController(cc) {

  def download = Action { implicit request =>
    val data = FormTool.fileNameForm.bindFromRequest().get
    val fileOp = Tool.underFileOp(Utils.path, data.fileName)
    fileOp.map { file =>
      Ok.sendFile(file)
        .withHeaders(
          CONTENT_DISPOSITION -> s"${Tool.getContentDisposition(file.getName)}",
          CONTENT_TYPE -> "application/x-download"
        )
    } getOrElse {
      NotFound("Resource not found!")
    }

  }

}
